package com.my.redisson.delayqueue.handler;

import com.my.redisson.domain.DelayEvent;
import com.my.redisson.enums.BizTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.EnumMap;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Component
public class DelayEventHandlerDispatcher {

    @Autowired
    private List<DelayEventHandler> handlers;

    private EnumMap<BizTypeEnum, DelayEventHandler> handlerMap;

    @Autowired
    private ThreadPoolExecutor executor;

    @PostConstruct
    public void init() {
        handlerMap = new EnumMap<>(BizTypeEnum.class);
        for (DelayEventHandler handler : handlers) {
            handlerMap.put(handler.getBizType(), handler);
        }
    }

    //    @Async("executor")
    public void handle(DelayEvent delayEvent) {
        executor.execute(() -> {
            BizTypeEnum bizTypeEnum = BizTypeEnum.ofBizType(delayEvent.getBizType());
            DelayEventHandler handler = handlerMap.get(bizTypeEnum);
            if (handler == null) {
                log.error("DelayEventHandlerDispatcher handler不存在 delayEvent:{} bizTypeEnum:{}", delayEvent, bizTypeEnum);
                return;
            }
            handler.handle(delayEvent);
        });
    }
}
